package log

import (
    "github.com/fatih/color"
    "gopkg.in/natefinch/lumberjack.v2"
    "fmt"
    "log"
    "os"
    "path/filepath"
)

var consoleLogger *log.Logger
var fileLogger *log.Logger

func Init(verbose bool, log_path string, logFileName string) {
    flags := int(log.Ldate | log.Ltime | log.Lmicroseconds)
    if verbose {
        consoleLogger = log.New(os.Stderr, "", flags)
    }
    rotate_file := &lumberjack.Logger{
        Filename:   filepath.Join(log_path, fmt.Sprintf("%v.log", logFileName)),
        MaxSize:    100,
        MaxBackups: 20,
        MaxAge:     1,
        LocalTime:  true,
    }
    fileLogger = log.New(rotate_file, "", flags)
}

func Info(format string, args ...interface{}) {
    if consoleLogger != nil {
        f := fmt.Sprintf("%s %s", color.GreenString("INFO"), format)
        consoleLogger.Output(2, fmt.Sprintf(f, args...))
    }
    f := fmt.Sprintf("%s %s", "INFO", format)
    fileLogger.Output(2, fmt.Sprintf(f, args...))
}

func Warning(format string, args ...interface{}) {
    if consoleLogger != nil {
        f := fmt.Sprintf("%s %s", color.YellowString("WARNING"), format)
        consoleLogger.Output(2, fmt.Sprintf(f, args...))
    }
    f := fmt.Sprintf("%s %s", "WARNING", format)
    fileLogger.Output(2, fmt.Sprintf(f, args...))
}

func Error(format string, args ...interface{}) {
    if consoleLogger != nil {
        f := fmt.Sprintf("%s %s", color.RedString("ERROR"), format)
        consoleLogger.Output(2, fmt.Sprintf(f, args...))
    }
    f := fmt.Sprintf("%s %s", "ERROR", format)
    fileLogger.Output(2, fmt.Sprintf(f, args...))
}
